package com.starbaba.module.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.starbaba.core.hibernate.DAOFactory;
import com.starbaba.core.hibernate.HibernateDAO;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.module.model.ModelVO;
import com.starbaba.module.model.ModuleVO;
import com.starbaba.module.model.Universal_model;
import com.starbaba.module.model.Universal_module;
import com.starbaba.module.service.IModelService;
import com.starbaba.redis.JedisUtils;
import com.starbaba.tools.sequence.Sequence;

@Component
@SuppressWarnings({"deprecation","unchecked","rawtypes"})
public class ModelServiceImpl implements IModelService {

    static BaseDao dao = new BaseDao(Constant.POOL_LIFE);
    static BaseDao testdao = new BaseDao(Constant.POOL_PUSH_RW);

    @Override
    public List getDataList(int iDisplayStart, int iDisplayLength, PageResponse pageResponse, Map<String, Object> paramsMap) {

        String prd_name = (String) paramsMap.get("prd_name");
        String status = (String) paramsMap.get("status");
        String pid = (String) paramsMap.get("pid");
        String name = (String) paramsMap.get("name");
        String type = (String) paramsMap.get("type");
        String orderby = (String) paramsMap.get("orderby");
        StringBuffer sf = new StringBuffer();
        StringBuffer tt = new StringBuffer();
        sf.append("select * From universal_model as m where 1=1 ");

        if (prd_name != null && prd_name != "") {
            tt.append(" and  m.demo like '%" + prd_name + "%'");
        }
        if (status != null && status != "") {
            tt.append(" and  m.status = " + status);
        }
        if (name != null && name != "") {
            tt.append(" and  m.name like '%" + name + "%'");
        }
        if (pid != null && pid != "") {
            tt.append(" and  (m.id = " + pid);
            tt.append(" or  m.parent_id = " + pid + ")");
        }
        if (type != null && type != "") {
            tt.append(" and  m.type = " + type);
        }
        sf.append(tt.toString());
        sf.append(" order by m.ctime " + orderby + " LIMIT " + iDisplayStart + "," + iDisplayLength);
        List<ModelVO> list = null;
        try {
            list = dao.list(sf.toString(), ModelVO.class, new Object[] {});

            String countHql = "select count(*) from universal_model as m where 1=1 " + tt.toString();
            int count = dao.getInt(countHql, new Object[] {});

            pageResponse.setITotalRecords(count);
            pageResponse.setITotalDisplayRecords(count);
        } catch (Exception e) {

        }
        return list;
    }

    @Override
    public void saveModule(Map<String, Object> paramsMap, String model_id) {

        HibernateDAO dao = DAOFactory.getInstance().createHibernateDAO(ModelVO.class);
        Session session = dao.getSession();
        JSONObject obj = new JSONObject();
        String content = (String) paramsMap.get("content");
        String name = (String) paramsMap.get("name");
        String value = (String) paramsMap.get("value");
        String memo = (String) paramsMap.get("memo");
        String s = (String) paramsMap.get("sp");

        // 前台传回来是一个字符串，根据@#切割换成数组
        String contents[] = content.split("@#");
        String names[] = name.split("@#");
        String values[] = value.split("@#");
        String memos[] = memo.split("@#");
        String splits[] = s.split("@#");

        dao.executeHQLUpdate("delete ModuleVO as m where m.model_id=?", Long.parseLong(model_id));// 删除每个模板里的内容

        int length = contents.length;
        // 重新保存每个模板里的内容
        for (int i = 0; i < length; i++) {
            ModuleVO moduleVO = new ModuleVO();
            moduleVO.setContent(contents[i]);
            moduleVO.setName(names[i]);
            moduleVO.setValue(values[i]);
            moduleVO.setMemo(memos[i]);
            moduleVO.setSplit(splits[i]);
            moduleVO.setCtime(new Date());
            Long modelid = Long.parseLong(model_id);
            moduleVO.setModel_id(modelid);
            moduleVO.setId(Sequence.getSequence());
            moduleVO.setType("string");
            String key = names[i];
            if (!splits[i].equals("*")) {
                String sp = splits[i];// 分隔标识符
                String jsonval[] = values[i].split(sp);
                obj.put(key.trim(), jsonval);
            } else if (splits[i].equals("*")) {// 特定的标示，标示不用分隔
                obj.put(key.trim(), values[i]);
            }

            try {
                // commonService.doCreate(ModuleVO.class, moduleVO);
                if (key.equals("campaign_type")) {
                    String campiagn_id = values[i];// value 值
                    List<ModelVO> list = (List<ModelVO>) dao.findByHQL("From ModelVO m where m.id=? ", Long.parseLong(model_id));
                    if (!list.isEmpty()) {
                        ModelVO modelVO = list.get(0);
                        modelVO.setCampiagn_id(Integer.parseInt(campiagn_id));
                        session.saveOrUpdate(modelVO);
                    }
                }
                session.merge(moduleVO);

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        List<ModelVO> list = (List<ModelVO>) dao.findByHQL("From ModelVO m where m.id=? ", Long.parseLong(model_id));
        if (!list.isEmpty()) {
            ModelVO modelVO = list.get(0);
            String key = "universal_" + modelVO.getId();
            JedisUtils.set(key, obj.toString());
        }
    }
    
    
    @Override
    public void copyModel(String model_id) {

        HibernateDAO dao = DAOFactory.getInstance().createHibernateDAO(ModelVO.class);
        Session session = dao.getSession();

        // List<ModuleVO> list = (List<ModuleVO>)
        // commonService.doFindByHQL("from ModuleVO t where t.model_id=?  ",
        // Long.parseLong("1"));

        if (model_id != null && model_id != "") {
            Long mid = Long.parseLong(model_id);
            List<ModelVO> shareList = (List<ModelVO>) dao.findByHQL("From ModelVO m where m.parent_id=? ", Long.parseLong(model_id));
            if (shareList.isEmpty()) {// 没有分享页
                saveCopyModel(session, dao, mid, false, null);
            } else {// 有分享页
                Long pid = saveCopyModel(session, dao, mid, false, null);// 保存分享活动模板
                for (ModelVO m : shareList) {
                    saveCopyModel(session, dao, m.getId(), true, pid);
                }
            }

        }

    }

    @Override
    public void copyModelToTest(String model_id) {

        // HibernateDAO dao =
        // DAOFactory.getInstance().createHibernateDAO(ModelVO.class);
        // Session session = dao.getSession();

        // List<ModuleVO> list = (List<ModuleVO>)
        // commonService.doFindByHQL("from ModuleVO t where t.model_id=?  ",
        // Long.parseLong("1"));

        try {
            if (model_id != null && model_id != "") {
                List<Universal_model> list = dao.list("select * from universal_model where id =? or parent_id =?", Universal_model.class, model_id, model_id);
                List<String> params = new ArrayList<String>();
                params.add(model_id);
                params.add(model_id);
                testdao.update("delete from universal_model where id =? or parent_id =?", params);
                String deleteSql = "delete from universal_module where model_id = ?";
                String moduleSql = "select * from universal_module where model_id = ?";
                for (Universal_model model : list) {
                    Long id = model.getId();
                    testdao.add(model);
                    testdao.update(deleteSql, id);
                    List<Universal_module> moduleList = dao.list(moduleSql, Universal_module.class, id);
                    for (Universal_module module : moduleList) {
                        testdao.add(module);
                    }
                }
            }
        } catch (AppException e) {
            e.printStackTrace();
        }

    }

    public Long saveCopyModel(Session session, HibernateDAO dao, Long model_id, boolean isShare, Long pid) {
        List<ModuleVO> list = (List<ModuleVO>) dao.findByHQL("from ModuleVO t where t.model_id=?  ", model_id);
        ModelVO model = (ModelVO) dao.findUniqueByHQL("From ModelVO m where m.id=? ", model_id);

        ModelVO modelVo = new ModelVO();
        Long modelId = Sequence.getSequence();
        modelVo.setId(modelId);
        modelVo.setType(model.getType());
        if (isShare) {
            modelVo.setName("新活动分享页");
            modelVo.setDemo("新活动分享页");
            modelVo.setDepth(1);
            modelVo.setParent_id(pid);

        } else {
            modelVo.setName("新活动");
            modelVo.setDemo("无");
            modelVo.setDepth(0);
        }

        modelVo.setStatus("1");
        modelVo.setCtime(new Date());
        session.save(modelVo);

        for (ModuleVO m : list) {
            ModuleVO moduleVo = new ModuleVO();
            moduleVo.setId(Sequence.getSequence());
            moduleVo.setName(m.getName());
            moduleVo.setContent(m.getContent());
            moduleVo.setModel_id(modelId);
            moduleVo.setCtime(new Date());
            moduleVo.setValue(m.getValue());
            moduleVo.setSplit(m.getSplit());
            moduleVo.setMemo(m.getMemo());
            moduleVo.setType(m.getType());
            try {
                // commonService.doCreate(ModuleVO.class, moduleVo);.
                session.save(moduleVo);
            } catch (Exception e) {

            }
        }
        return modelId;
    }

    @Override
    public void delModel(String model_id) {
        if (model_id != null && model_id != "") {

            HibernateDAO dao = DAOFactory.getInstance().createHibernateDAO(ModelVO.class);
            dao.executeHQLUpdate("update ModelVO as m set m.status=0 where m.id=?", Long.parseLong(model_id));
            // update User user set user.age=20 where user.age=18”;
            // ModelVO m=(ModelVO)
            // dao.findUniqueByHQL("from ModelVO t where t.id=?",
            // Long.parseLong(model_id));

            // dao.deleteByVO(m);

            String key = "universal_" + model_id;

            JedisUtils.del(key);
        }
    }

    @Override
    public void onlineModel(String id) {

        if (id != null && id != "") {
            HibernateDAO dao = DAOFactory.getInstance().createHibernateDAO(ModelVO.class);
            dao.executeHQLUpdate("update ModelVO as m set m.status=1 where m.id=?", Long.parseLong(id));

            List<ModuleVO> list = (List<ModuleVO>) dao.findByHQL("from ModuleVO t where t.model_id=?  ", Long.parseLong(id));

            JSONObject obj = new JSONObject();
            for (ModuleVO m : list) {
                String sp = m.getSplit();

                if (!sp.equals("*")) {
                    String val = m.getValue();
                    String jsonval[] = val.split(sp);
                    obj.put(m.getName(), jsonval);
                } else {
                    obj.put(m.getName(), m.getValue());
                }
            }

            String key = "universal_" + id;
            JedisUtils.set(key, obj.toString());

        }
    }
}